/**
 * Adds polylines as contour segmentation annotations to a segmentation.
 *
 * Each polyline is associated with a view reference and is added as a new annotation
 * for the specified segment index. The function updates the annotationUIDsMap to include
 * the new annotation UIDs for the segment.
 *
 * @param viewport The Cornerstone3D viewport where the annotation will be added
 * @param annotationUIDsMap Map from segment index to set of annotation UIDs
 * @param segmentationId The ID of the segmentation
 * @param polylinesInfo Array of PolylineInfoWorld ({ polyline, viewReference }) to add
 * @param segmentIndex The segment index to which the polylines belong
 * @returns The updated annotationUIDsMap
 */

import type { Types } from '@cornerstonejs/core';
import { utilities } from '@cornerstonejs/core';
import { addAnnotation } from '../../stateManagement';
import type { PolylineInfoWorld } from './polylineInfoTypes';

const DEFAULT_CONTOUR_SEG_TOOLNAME = 'PlanarFreehandContourSegmentationTool';

export default function addPolylinesToSegmentation(
  viewport: Types.IViewport,
  annotationUIDsMap: Map<number, Set<string>>,
  segmentationId: string,
  polylinesInfo: PolylineInfoWorld[],
  segmentIndex: number
) {
  polylinesInfo.forEach(({ polyline, viewReference }) => {
    if (polyline.length < 3) {
      return;
    }

    const contourSegmentationAnnotation = {
      annotationUID: utilities.uuidv4(),
      data: {
        contour: {
          closed: true,
          polyline,
        },
        segmentation: {
          segmentationId,
          segmentIndex,
        },
        handles: {},
      },
      handles: {},
      highlighted: false,
      autoGenerated: false,
      invalidated: false,
      isLocked: false,
      isVisible: true,
      metadata: {
        toolName: DEFAULT_CONTOUR_SEG_TOOLNAME,
        ...viewReference,
      },
    };

    addAnnotation(contourSegmentationAnnotation, viewport.element);

    const currentSet = annotationUIDsMap?.get(segmentIndex) || new Set();
    currentSet.add(contourSegmentationAnnotation.annotationUID);
    annotationUIDsMap.set(segmentIndex, currentSet);
  });
  return annotationUIDsMap;
}
